package com.liao.seckill.utils;

import com.liao.seckill.constant.UserConstant;
import com.liao.seckill.pojo.TbUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtTokenUtil {

    private static final String SECRET = "a_>+123";

    public static String generateToken(TbUser tbUser) {
        long l = System.currentTimeMillis() + UserConstant.TOKEN_EXPIRED_TIME * 1000;
        return Jwts.builder()
                .setSubject(tbUser.getUsername())
                .claim("id",tbUser.getId())
                .claim("username",tbUser.getUsername())
                .setIssuedAt(new Date())//签发时间
                .setExpiration(new Date(l))//过期时间
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    public static Claims getInfoFromToken(String authToken) throws Exception {
//        try {
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(authToken).getBody();
//        } catch (ExpiredJwtException e) {
//            throw new UserTokenException("Token过期!");
//        } catch (SignatureException e){
//            throw new UserTokenException("Token错误!");
//        }
    }

}
